package com.excel.sys.controller;

import com.excel.sys.service.ExportExcelService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalTime;

@Controller
@RequestMapping("excel")
public class  ExportExcelController {

    @Autowired
    ExportExcelService service;

    @GetMapping("")
    public String getExportExcelHtml(){
        return "ExportExcel";
    }

    @GetMapping("export")
    public void exportExcel(HttpServletResponse response) {
        try {
            Workbook wb = service.exportExcel();
            //获取 当前时间 格式：年月日时分秒
            LocalTime time = LocalTime.now();
            String strdate = LocalDate.now().toString().replace("-","");
            String times = time.getHour()+""+time.getMinute()+""+time.getSecond()+"";
            //编辑 Excel 的 文件名
            String fileName = "users - "  + strdate + times + ".xls";
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"),"iso-8859-1"));
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("export2")
    public void exportExcel2(HttpServletResponse response) {
        try {
            Workbook wb = service.exportExcel2();
            //获取 当前时间 格式：年月日时分秒
            LocalTime time = LocalTime.now();
            String strdate = LocalDate.now().toString().replace("-","");
            String times = time.getHour()+""+time.getMinute()+""+time.getSecond()+"";
            //编辑 Excel 的 文件名
            String fileName = "users - "  + strdate + times + ".xls";
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
